package com.jiajia.study.netty.chapter01;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class MyNettyClient {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.channel(NioSocketChannel.class);
        /**
         * 为什么在 client 端，也要引入事件循环组：
         *  1. 统一编程模型
         *  2. 异步操作：连接一个线程，读写通信做成一个线程
         */
        bootstrap.group(new NioEventLoopGroup());

        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ch.pipeline().addLast(new StringEncoder());
            }
        });
        // 创建线程，进行连接操作
        ChannelFuture connect = bootstrap.connect(new InetSocketAddress(9999));
        // 阻塞连接，直到连接完成
        connect.sync();
        // 获取连接完成的 channel
        Channel channel = connect.channel();
        // 写入数据
        channel.writeAndFlush("hello,netty ");
    }
}
